import * as mqtt from "mqtt/dist/mqtt";
import { getUser, setClientTime, getSn } from '@/utils/publicMethods'

export default function () {
  const wss = import.meta.env.VITE_SERVER_BASEURL__WSS_DEVELOP
  const phoneNumber = getUser('phoneNumber') ? getUser('phoneNumber').slice(-4) : '0000'
  const loginTime = getUser('loginTime') ? getUser('loginTime').slice(-7) : '0000000'
  const mqttData = ref({
    client: null,
    connection: {
      keepalive: 60, //60秒
      clean: false, //设置为 false 以在脱机时接收 QoS 1 和 2 消息
      connectTimeout: 120 * 1000, //120 * 1000 毫秒，收到 CONNACK 之前的等待时间，超时时间
      reconnectPeriod: 4000, //4 * 1000 毫秒，两次重连之间的间隔。通过设置为 0 来禁用自动重新连接
      clientId: `${phoneNumber}_${uni.getDeviceInfo().platform}_${loginTime}`,
      username: 'xinkang-test',
      password: 'qwert12345'
    },
  })

  const operation = ref({
    retryTimes: 0, //重试时间
    maxRetryTimes: 10, //最大重连次数
  })

  const setOperation = ref({
    sn: '',
    qos: 1,
    topic: [],
    payload: '{ "msg": "Hello, mqtt测试请求" }'
  })

  // 初始化
  const initData = () => {
    operation.value.retryTimes = 0;
    mqttData.value.client = null
  };


  // 切断连接
  const destroyConnection = () => {
    return new Promise((resolve, reject) => {
      if (mqttData.value.client?.connected) {
        try {
          mqttData.value.client.end(false, () => {
            initData();
            resolve(true)
            console.log("已关闭mqtt连接");
          });
        } catch (error) {
          console.log("关闭mqtt连接异常:", error);
          resolve(false)
        }
      } else {
        resolve(false)
      }
    })
  };

  // 关闭订阅
  const doUnSubscribe = (topic, qos) => {
    const topicList = topic ? [topic] : setOperation.value.topic
    const qos_ = (qos || qos) === 0 ? qos : setOperation.value.qos
    if (!mqttData.value.client?.connected) return
    topicList.forEach(item => {
      mqttData.value.client.unsubscribe(item, { qos: qos_ }, (error) => {
        if (error) {
          console.log('item', error)
        }
      })
    })
  }

  // 开启订阅
  const doSubscribe = (topic, qos) => {
    return new Promise((resolve, reject) => {
      const topic_ = topic || setOperation.value.topic
      const qos_ = (qos || qos) === 0 ? qos : setOperation.value.qos
      mqttData.value.client.subscribe(topic_, { qos: qos_ }, (error, granted) => {
        if (error) {
          console.log("开启订阅异常:", error);
          resolve(false)
        } else {
          console.log("开启订阅成功！:", granted);
          resolve(true)
        }
      });
    })
  };

  // 创建连接
  const createConnection = () => {
    return new Promise((resolve, reject) => {
      console.log('mqtt连接状态', mqttData.value.client?.connected)
      if (mqttData.value.client?.connected) {
        console.log("已连接过，无需再次连接");
        resolve(true)
        return
      }
      try {
        const { ...options } = mqttData.value.connection
        mqttData.value.client = mqtt.connect(wss, options);
        // 是否存在监听事件
        if (mqttData.value.client.on) {
          // 创建连接
          mqttData.value.client.on("connect", () => {
            resolve(true)
            setOperation.value.sn = getSn()
            setClientTime(new Date().getTime())
            console.log("创建新连接成功", new Date().toISOString().slice(11, 19));
          });
          // 重连
          mqttData.value.client.on("reconnect", () => {
            operation.value.retryTimes += 1;
            if (operation.value.retryTimes > operation.value.maxRetryTimes) {
              resolve(false)
              mqttData.value.client.end();
              console.log("重连超出限制，停止重试");
            }
          });
          // 连接异常
          mqttData.value.client.on("error", error => {
            resolve(false)
            console.log("连接异常:", error);
          });
          mqttData.value.client.on('offline', () => {
            resolve(false)
            console.log('连接丢失');
          });
          mqttData.value.client.on('end', () => {
            resolve(false)
            console.log('连接已关闭')
          })
          // 接收消息
          mqttData.value.client.on("message", (topic, message) => {
            resolve(true)
            const useMessage = JSON.parse(message.toString())
            uni.$emit('subscription', { topic, message: useMessage })
          })
        }
      } catch (error) {
        resolve(false)
        console.log("创建连接异常:", error);
      }
    })

  };

  return {
    mqttData,
    operation,
    setOperation,
    initData,
    doSubscribe,
    doUnSubscribe,
    destroyConnection,
    createConnection
  }

}


